{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://mp.weixin.qq.com/s?__biz=MzkxODE3NjExOQ==&mid=2247485407&idx=1&sn=582c58614c91bfce798888a1cd2ad075&chksm=c1b42fc7f6c3a6d1e1ab94d7791d99ece2758acf22f3a81d346196eb70af0440dfdf173d5a41&scene=178&cur_album_id=3354758663365918722#rd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入需要使用的库\n",
    "import akshare as ak\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "# 关闭警告信息\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 获取沪深300指数10年的收盘价数据\n",
    "start_date = '20140101'  # 开始日期\n",
    "end_date = '20231229'  # 结束日期\n",
    "bars = ak.stock_zh_index_hist_csindex(symbol='000300', start_date=start_date, end_date=end_date)\n",
    "price_df = bars[['日期','收盘']]\n",
    "# 将日期设置为datetime格式\n",
    "price_df['日期'] = pd.to_datetime(price_df['日期'])\n",
    "price_df.set_index('日期', inplace=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算日收益率\n",
    "returns = price_df['收盘'].pct_change()\n",
    "n = len(returns)\n",
    "\n",
    "# 计算下行差异\n",
    "downside_returns = np.clip(returns, -np.inf, 0)\n",
    "\n",
    "# 计算下行波动率\n",
    "downside_variance = np.sum(downside_returns ** 2) / n\n",
    "downside_risk = np.sqrt(downside_variance * 244)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "4broker",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
